<?php
namespace app\admin\controller;

use app\admin\model\ReserveSetInfo;
use think\Controller;
use app\admin\model\User as Users;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\UserInfo;
use app\admin\model\FrontUser as FrontUser;
use app\admin\model\Reserve;
use think\Db;
use think\Request;
use PHPExcel_IOFactory;
use PHPExcel;

/*****
 *
 *  乐8小城订场管理模块
 *
 */

class Consumer extends Common
{
    private $Reserve;   //当前控制器关联模型
    private $FrontUser;   //当前控制器关联模型

    public function _initialize()
    {
        parent::_initialize();
        $this->Reserve = new Reserve;   //别名：避免与控制名冲突
    }

    public function index(Request $request)
    {
        $where = [];
        //关键字
        if (input('get.search')){
            $where['name|mobile|membercard'] = ['like', '%'.input('get.search').'%'];
        }
        $usage = input('get.usage');

        if ($usage){
            $where['usage'] = $usage;
        }
        $reserve_date = input('get.reserve_date');
        if ($reserve_date !=''){
            $where['reserve_date'] = $reserve_date;
        }

        $order = 'id desc';

        $dataList = $this->Reserve->where($where)->order($order)->paginate('', false, page_param());
        //处理昨天之前所有待入场状态 修改为未到场
        /*$date = date('Y-m-d',strtotime('-1 day'));
        $this->Reserve->where('create_time','<= time','2016-1-1');*/

        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    //修改预约状态
    public function create()
    {
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $result = $this->Reserve->where('id',$data['id'])->update(['usage'=>$data['usage']]);
                //如果是取消恢复订场人数
                if($data['usage'] == 6){
                    $re = $this->Reserve->where('id',$data['id'])->find();
                    $ri = new ReserveSetInfo();
                    $ri->where('reserve_date',$re['reserve_date'])->where('field',$re['reserve_field'])->setInc('num',$re['people_num']);
                }

                // 提交事务
                if ($result){
                    Db::commit();
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        }else{
            return $this->fetch('create');
        }
    }

    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            $id = input('post.id');
            $arr = [
                'mobile'=>$data['mobile'],
                'name'=>$data['name'],
                'adult'=>$data['adult'],
                'kid'=>$data['kid'],
                'usage'=>$data['usage']
            ];
            $res = $this->Reserve->where('id',$id)->update($arr);

            if ($res){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->Reserve->getError());
            }
        }else{
            //搜索预约信息

            if ($id > 0){
                $data = DB::table('tf_reserve')
                    ->alias('tr')
                    ->join('tf_front_user fu','tr.fu_id = fu.id','left')
                    ->where('tr.id',$id)
                    ->field('tr.*,fu.username')
                    ->find();
                //echo FrontUser::getLastSql();
                //dump($data);exit;
                $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
                $this->assign('data', $data);
                return $this->fetch();
            }
        }
    }

    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                Db::startTrans();
                try{
                    $id_arr = explode(',', $id);   //用户数据
                    $where = [ 'id' => ['in', $id_arr] ];
                    $result = $this->Reserve->where($where)->delete();   //删除主表数据
                    // 提交事务
                    if ($result){
                        Db::commit();
                        return ajaxReturn(lang('action_success'), url('index'));
                    }else{
                        return ajaxReturn($this->Reserve->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajaxReturn($e->getMessage());
                }
            }
        }
    }

    public function authGroup($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            $id = $data['id'];
            $group = $data['group'];
            $where = ['id' => $id];
            $this->FrontUser->where('id',$id)->update(['group'=>$group]);
            return ajaxReturn(lang('action_success'), url('index'));
        }else{
            if ($id > 0){
                $data = $this->FrontUser->find($id);
                $this->assign('data', $data);
                return $this->fetch();
            }
        }
    }

    //导出
    public function export(){
        $laterArray = $this->Reserve->order('reserve_date desc')->select();//查找user表数据
        $xlsName = "订场统计";
        $xlsCell = array(
            array('reserve_date','预约日期'),
            array('name','姓名'),
            array('mobile','预约手机'),
            array('membercard','会员卡号'),
            array('reserve_field','场次'),
            array('usage','预约状态'),
            array('adult','成年人'),
            array('kid','小孩'),
            array('people_num','总人数'),
        );//查出字段输出对应Excel对应的列名
        //替换字段状态
        foreach ($laterArray as $key=>$val){
            $laterArray[$key]['reserve_field'] = config('rfield')[$laterArray[$key]['reserve_field']];
            $laterArray[$key]['usage'] = config('reserve_status')[$laterArray[$key]['usage']];
        }


        //公共方法调用
        $this->export_excel($xlsName,$xlsCell,$laterArray);
    }

    /**
     * 公共数据导出实现功能
     * @param $expTitle 导出文件名
     * @param $expCellName 导出文件列名称
     * @param $expTableData 导出数据
     */
    function export_excel($expTitle,$expCellName,$expTableData)
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle . date('_Ymd');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $objPHPExcel = new PHPExcel();//方法一
        $cellName = array('A','B', 'C','D', 'E', 'F','G','H','I', 'J', 'K','L','M', 'N', 'O', 'P', 'Q','R','S', 'T','U','V', 'W', 'X','Y', 'Z', 'AA',
            'AB', 'AC','AD','AE', 'AF','AG','AH','AI', 'AJ', 'AK', 'AL','AM','AN','AO','AP','AQ','AR', 'AS', 'AT','AU', 'AV','AW', 'AX',
            'AY', 'AZ');
        //设置头部导出时间备注
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . ' 导出时间:' . date('Y-m-d H:i:s'));
        //设置列名称
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        //赋值
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue(
                    $cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]
                );
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
        $objWriter = \PHPExcel_IOFactory::createWriter(
            $objPHPExcel, 'Excel5'
        );//"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
        $objWriter->save('php://output');
    }


}